<template>
	<view>
		<u-popup :show="show" @close="close">
			<view class="btn-content">
				<button class="login-btn" size="mini" open-type="getPhoneNumber" @getphonenumber="getphonenumber">
					一键登录
				</button>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {
		getOpenId,
		getUserInfo,
		getUserPhoneNum,
	} from '@/api/index'
	export default {
		data() {
			return {
				show: false
			}
		},
		methods: {
			showPopup() {
				this.show = true
			},
			close() {
				this.show = false
			},
			//登录
			toLogin() {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						this.getOpenId(res.code)
					},
					fail: (err) => {
						uni.$u.toast('登录失败')
					}
				})
			},
			//获取微信openid
			getOpenId(code) {
				uni.showLoading({
					title: '登录中...'
				})
				getOpenId({
					code
				}).then(res => {
					const openId = res.data.open_id
					this.getUserInfo(openId)
				}).finally(() => {
					uni.hideLoading()
				})
			},
			//获取用户手机号
			getUserPhoneNum(code) {
				uni.showLoading({
					title: '请求中...'
				})
				getUserPhoneNum({
					code
				}).then(res => {
					this.phone = res.data.phoneNumber;
					console.log('获取到手机号', this.phone)
					//登录
					this.toLogin()
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getphonenumber(e) {
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					uni.$u.toast('获取手机号失败，请重试')
					return
				}
				this.getUserPhoneNum(e.detail.code)
			},
			//获取用户信息
			getUserInfo(openId) {
				if (!openId) {
					return
				}
				const params = {
					open_id: openId
				}
				uni.showLoading({
					title: '加载中...'
				})
				getUserInfo(params).then(res => {
					const data = res.data?.data[0] || {}
					this.$store.commit('SET_USER_INFO', data)
					this.$emit('refreshUserInfo')
				}).finally(() => {
					uni.hideLoading()
					this.close()
				})
			},
		}
	}
</script>
<style scoped>
	.btn-content {
		display: flex;
		justify-content: center;
		padding: 48rpx;
	}

	.login-btn {
		border: none;
		background-color: #19be6b;
		color: #fff;
		margin-top: 20rpx;
		font-size: 32rpx;
	}
</style>